package com.gz.mylife.app.keys;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.gz.mylife.App;
import com.gz.mylife.R;
import com.gz.mylife.util.PrefUtils;
import com.gz.mylife.util.SendUdp;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.zl.smartmall.library.po.DeviceBean;
import com.zl.smartmall.library.po.KeysData;
import com.zl.smartmall.library.po.KeysData.Ref;
import com.zl.smartmall.library.po.Res;
import com.zl.smartmall.library.util.Constants;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class DoorFragment extends Fragment implements OnRefreshListener<ListView>{
	private View mConvertView;
	private SensorManager sensorManager;
	private Vibrator vibrator;
	private static final int SENSOR_SHAKE = 10;
	private static final int REFRESH = 20;
	private static final int INTENET_CHANGER = 30;
	private List<DeviceBean> mDeviceList ;
	private List<Res> mOpenList = new ArrayList<Res>();
	private List<Ref> mKeysList = new ArrayList<Ref>();
	private PullToRefreshListView refListView;
	private ListViewAdapter adapter;
	private Button transfer;
	private LayoutInflater mInflater;
	private RelativeLayout logo_info;
	private ProgressBar pb_progress;
	private TextView tv_hint;
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mConvertView == null) {
			mConvertView = inflater.inflate(R.layout.activity_doorlist,
					container, false);
		}
		sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);// 传感器
		vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);// 震动器

		mInflater = getLayoutInflater(savedInstanceState);
		transfer = (Button) mConvertView.findViewById(R.id.transfer);
		transfer.setVisibility(View.GONE);

		logo_info = (RelativeLayout) mConvertView.findViewById(R.id.logo_info);
		pb_progress = (ProgressBar) mConvertView.findViewById(R.id.pb_progress);
		tv_hint = (TextView) mConvertView.findViewById(R.id.tv_hint);

		refListView = (PullToRefreshListView) mConvertView.findViewById(R.id.listchance);
		adapter = new ListViewAdapter();
		refListView.setOnRefreshListener(this);
		refListView.setAdapter(adapter);

		sendmessage();

		StateChanageReceiver StateReceiver = new StateChanageReceiver();
		IntentFilter filter = new IntentFilter(); 
		filter.addAction("getUdpMssage");
		getActivity().registerReceiver(StateReceiver, filter);
		logo_info.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pb_progress.setVisibility(View.VISIBLE);
				tv_hint.setVisibility(View.VISIBLE);
				tv_hint.setText("卖命加载中...");
				sendmessage();
			}
		});
		return mConvertView;
	}

	private void initData() {
		initListData();
	}
	/**
	 * 摇一摇 - 动作执行
	 */
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {

			case REFRESH:
				initData();
				if (refListView.isRefreshing()) {
					refListView.getLoadingLayoutProxy().refreshSuccess(); 
				}
				break;

			case INTENET_CHANGER:
				initData();
				break;

			case SENSOR_SHAKE:
				final String devId = App.devicelist.get(0).getDev_id();
				final String devIp = App.devicelist.get(0).getDev_ip();
				final String devMac = App.devicelist.get(0).getDev_mac();
				String devType = App.devicelist.get(0).getDev_type();

				final String dir = mOpenList.get(0).direction;
				new Thread(){
					public void run() {
						App.appip = devIp;
						//如果2中情况下， 1,是进，2是出。 如果是一种情况下，就直接1
						if(dir.equals("只入")){
							App.sendtype="1";
						}else{
							App.sendtype="2";
						}
						String message = devMac+",OPENBEG,"+"001";
						SendUdp.sendmessageopen(message,"10.10.100.254");
					};
				}.start();
				Toast.makeText(getActivity(), "已开启！", Toast.LENGTH_SHORT).show();
				break;
			}
		}

	};
	class StateChanageReceiver extends BroadcastReceiver {//改变无线网络接收的广播
		@Override
		public void onReceive(Context context, Intent intent) {
			sendmessage();
		}
	}

	// 开门列表数据
	private void initListData() {
		String keysJson = PrefUtils.getStrPrefData(getActivity(),Constants.KEYS_URL, "");// 读缓存(钥匙的集合)
		Gson gson = new Gson();
		KeysData mKeysData = gson.fromJson(keysJson, KeysData.class);
		if (mKeysData != null) {
			mKeysData.ref.addAll(mKeysData.msg);
			mKeysList = mKeysData.ref;
		}
		mOpenList.clear();
		mDeviceList = App.devicelist;// 门的集合

		if (mDeviceList!=null&&!keysJson.equals("")) {
			Log.e("mt", "开始匹配门数据");
			for (int i = 0; i < mDeviceList.size(); i++) {
				String devId = mDeviceList.get(i).getDev_mac();
				for(int x=0;x<mKeysList.size();x++){
					String controllerSn = mKeysList.get(x).getController_sn();
					if (devId.equals(controllerSn)) { // 判断门与钥匙是否匹配
						Ref ref = mKeysList.get(x);
						String direction = ref.getDirection();
						if (direction.equals("双向")) {// 如果服务返回的权限是"双向"(能进能出) 就把这条数据拆分为"进" "出"两条 添加到mOpenList集合
							Res r = new Res();
							r.begin_date = ref.getBegin_date();
							r.end_date = ref.getEnd_date();
							r.community_id = ref.getCommunity_id();
							r.controller_name = ref.getController_name();
							r.controller_sn = ref.getController_sn();
							r.controller_type = ref.getController_type();
							r.direction = "进";
							r.name = ref.getName();
							mOpenList.add(r);
							Res re = new Res();
							re.begin_date = ref.getBegin_date();
							re.end_date = ref.getEnd_date();
							re.community_id = ref.getCommunity_id();
							re.controller_name = ref.getController_name();
							re.controller_sn = ref.getController_sn();
							re.controller_type = ref.getController_type();
							re.direction = "出";
							re.name = ref.getName();
							mOpenList.add(re);
						}else {
							Res re = new Res();
							re.begin_date = ref.getBegin_date();
							re.end_date = ref.getEnd_date();
							re.community_id = ref.getCommunity_id();
							re.controller_name = ref.getController_name();
							re.controller_sn = ref.getController_sn();
							re.controller_type = ref.getController_type();
							re.direction = ref.getDirection();
							re.name = ref.getName();
							mOpenList.add(re);
						}

					}

				}
			}
			adapter.notifyDataSetChanged();
			if (refListView.isRefreshing()) {
				refListView.getLoadingLayoutProxy().refreshSuccess();
			}
		}

		Log.e("mt", "listView设置适配器完成");
		if (mOpenList.size()>0) {
			logo_info.setVisibility(View.GONE);
		}else{
			logo_info.setVisibility(View.VISIBLE);
			pb_progress.setVisibility(View.GONE);
			tv_hint.setText("暂无通道");
		}
		if (mOpenList.size()>0) {
			Log.e("mt", "listView设置条目点击事件");
			//listview 条目事件
			refListView.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> parent, final View view,
						int position, long id) {
					position = position-1;
					Log.e("mt", "点击了第"+position);
					if(mOpenList.size()>0){
						String controllerSn = mOpenList.get(position).controller_sn;
						for (int i = 0; i < App.devicelist.size(); i++) {
							if (controllerSn.equals(App.devicelist.get(i).getDev_mac())) {
								final String devId = App.devicelist.get(i).getDev_id();
								final String devIp = App.devicelist.get(i).getDev_ip();
								final String devMac = App.devicelist.get(i).getDev_mac();
								final String dir = mOpenList.get(position).direction;
								new Thread(){
									public void run() {
										App.appip = devIp;
										//如果2中情况下， 1,是进，2是出。 如果是一种情况下，就直接1
										if (dir.equals("进")) {
											App.sendtype="1";
										}else if(dir.equals("出")){
											App.sendtype="2";
										}else if(dir.equals("只入")){
											App.sendtype="1";
										}else{
											App.sendtype="2";
										}
										String message = devMac+",OPENBEG,"+devId;
										Log.i("ch", "传入发送ip="+devIp);
										App.tagip=devIp;
										SendUdp.sendmessageopen(message,App.tagip);
									};
								}.start();
							}
						}
					}

				}});
		}
	}
	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		Log.e("mt","开始下拉刷新");
		App.devicelist.clear();
		Log.e("mt","AppContext.devicelist.clear()完成,size=="+App.devicelist.size());
		Log.e("mt","开始查找设备");
		SendUdp.sendmessagefind();
		Log.e("mt","设备查找结束");
		new Thread(){
			public void run() {
				try {
					sleep(1500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mOpenList.clear();
				Log.e("mt","AppContext.devicelist.size=="+App.devicelist.size());
				Log.e("mt","mOpenList.size=="+mOpenList.size());

				Message msg = handler.obtainMessage();
				msg.what = REFRESH; 
				handler.sendMessage(msg);

			};
		}.start();
	}

	private class ListViewAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mOpenList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mOpenList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_open, null);
				holder = new ViewHolder();
				holder.door_item = (RelativeLayout) convertView.findViewById(R.id.door_item);
				holder.tvAddressopen = (TextView) convertView.findViewById(R.id.tv_address);
				holder.tvInfo = (TextView) convertView.findViewById(R.id.tv_info);
				holder.tvBtn = (TextView) convertView.findViewById(R.id.tv_btn);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			Res res = mOpenList.get(position);
			holder.tvAddressopen.setText(res.name);
			holder.tvInfo.setText(res.controller_name);
			holder.tvBtn.setText(res.direction);
			
			holder.tvBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(mOpenList.size()>0){
						String controllerSn = mOpenList.get(position).controller_sn;
						for (int i = 0; i < App.devicelist.size(); i++) {
							if (controllerSn.equals(App.devicelist.get(i).getDev_mac())) {
								final String devId = App.devicelist.get(i).getDev_id();
								final String devIp = App.devicelist.get(i).getDev_ip();
								final String devMac = App.devicelist.get(i).getDev_mac();
								final String dir = mOpenList.get(position).direction;
								new Thread(){
									public void run() {
										App.appip = devIp;
										//如果2中情况下， 1,是进，2是出。 如果是一种情况下，就直接1
										if (dir.equals("进")) {
											App.sendtype="1";
										}else if(dir.equals("出")){
											App.sendtype="2";
										}else if(dir.equals("只入")){
											App.sendtype="1";
										}else{
											App.sendtype="2";
										}
										String message = devMac+",OPENBEG,"+devId;
										Log.i("ch", "传入发送ip="+devIp);
										App.tagip=devIp;
										SendUdp.sendmessageopen(message,App.tagip);
									};
								}.start();
							}
						}
					}
				}
			});
			
			return convertView;
		}
	}
	private class ViewHolder {
		TextView tvAddressopen;
		TextView tvInfo;
		TextView tvBtn;
		RelativeLayout door_item;

	}

	/**
	 * 重力感应监听
	 */
	private SensorEventListener sensorEventListener = new SensorEventListener() {

		@Override
		public void onSensorChanged(SensorEvent event) {
			// 传感器信息改变时执行该方法
			float[] values = event.values;
			float x = values[0]; // x轴方向的重力加速度，向右为正
			float y = values[1]; // y轴方向的重力加速度，向前为正
			float z = values[2]; // z轴方向的重力加速度，向上为正
			// 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
			int medumValue = 17;// 三星怎么晃都不会超过20，没办法，只设置19了
			if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {
				if (mOpenList.size()==1) {

					Message msg = new Message();
					msg.what = SENSOR_SHAKE;
					handler.sendMessage(msg);
					vibrator.vibrate(400);
				}
				if (mOpenList.size()>1) {
					Toast.makeText(getActivity(), "请手动选择", 0).show();
					vibrator.vibrate(400);
				}
			}
		}
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}
	};
	
	@Override
	public void onPause() {
		super.onPause();
		if (sensorManager != null) {// 取消摇一摇监听器
			sensorManager.unregisterListener(sensorEventListener);
		}
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (sensorManager != null) {// 注册摇一摇监听器
			sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
			// 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
		}
	}

	public void sendmessage(){
		App.devicelist.clear();
		App.type="find";
		SendUdp.sendmessagefind();
		new Thread(){
			public void run() {
				try {
					sleep(1500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mOpenList.clear();
				Message mes = handler.obtainMessage();
				mes.what = INTENET_CHANGER;
				handler.sendMessage(mes);
			};
		}.start();
	}


}
